package site.lanmushan.framework.mapper.util;

import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;

import java.util.Set;

/**
 * @author Administrator
 */
public class SlashSqlHelper {
    public static Boolean isNotNull(Object obj) {
        return !isNull(obj);
    }

    public static Boolean isNull(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String) {
            return "".equals(((String) obj).trim());
        }
        return false;
    }

    public static String createSqlFrom(String tableName) {
        String sql = "  <choose>\n" +
                "            <when test=\"@site.lanmushan.framework.mapper.util.SlashSqlHelper@isNotNull(query.tableName)\">\n" +
                "                from ${query.tableName} as ${query.alias}\n" +
                "            </when>\n" +
                "            <otherwise>\n" +
                "                from %s as ${query.alias}\n" +
                "            </otherwise>\n" +
                "        </choose>";
        return String.format(sql, tableName);
    }
    public static String createSqlTableName(String tableName) {
        String sql = "  <choose>\n" +
                "            <when test=\"@site.lanmushan.framework.mapper.util.SlashSqlHelper@isNotNull(query.tableName)\">\n" +
                "                 ${query.tableName} as ${query.alias}\n" +
                "            </when>\n" +
                "            <otherwise>\n" +
                "                 %s as ${query.alias}\n" +
                "            </otherwise>\n" +
                "        </choose>";
        return String.format(sql, tableName);
    }
    public static String createSqlColumns(Class entityClass) {
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        String sql = "  <choose>\n" +
                "            <when test=\"@site.lanmushan.framework.mapper.util.SlashSqlHelper@isNotNull(query.columns)\">\n" +
                "                ${@site.lanmushan.framework.mapper.util.QueryWrapperUtil@createColumnsString(query)}\n" +
                "            </when>\n" +
                "            <otherwise>\n" +
                "                 %s \n" +
                "            </otherwise>\n" +
                "        </choose>";
        StringBuilder sb=new StringBuilder();
        sb.append("<trim suffixOverrides=\",\">");
        for (EntityColumn column : columnSet) {
            sb.append("${query.alias}." + column.getColumn()+",");
        }
        sb.append("</trim>");
        System.out.println(String.format(sql, sb.toString()));
        return String.format(sql, sb.toString());
    }
}
